import axios from 'axios'
import qs from 'qs'
import * as mockData from '~plugins/mocks'
export function request (method, url, params = {}, opts) {
  if (process.BROWSER_BUILD) {
    // let isSameOrigin = url.match(new RegExp(location.origin))
    method = method.toLowerCase()

    opts = {
      method: method,
    //   withCredentials: !!isSameOrigin,
      headers: {
        // 'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded'
        // 'Content-Type': 'application/json'
        // 'X-Requested-With': 'XMLHttpRequest'
      },
      params: {},
      data: {},
      ...opts
    }
    if (method === 'get' || method === 'delete') {
      opts.params = params
    } else {
      opts.data = qs.stringify(params)
    }
    let error = (status) => {
      let ret = {success: false, msg: '网络异常，请稍后重试'}
      if (status * 1 >= 500 || status * 1 <= 599) {
        ret.msg = '服务器维护中，请稍后重试'
      }
      return ret
    }
    let ret = {success: true, msg: '操作成功'}
    let fetchResponseError = (data) => {
      return typeof data === 'string' ? data.match(/<p\s+class="weui-msg__desc">(.*?)<\/p>/) : false
    }
    let reduceResponse = (data) => {
      let err = fetchResponseError(data)
      if (err) {
        ret.success = false
        ret.msg = err[1]
      } else if (!data || typeof data === 'string' || Array.isArray(data)) {
        ret.data = data
      } else {
        ret = {...ret, ...data}
      }
      return ret
    }
    if (opts.mock && mockData[opts.mock]) {
      let data = mockData[opts.mock]()
      return reduceResponse(data)
    } else {
      return axios(url, opts).then(res => {
        return res.status === 200 ? reduceResponse(res.data) : error(res.status)
      }).catch(() => error(0))
    }
  } else {
    return null
  }
}

export const get = (...args) => request('GET', ...args)
export const post = (...args) => request('POST', ...args)
